<?php
require_once(__DIR__ . '/../config.php');

use \Tuanduimao\Loader\App as App;
use \Tuanduimao\Utils as Utils;
use \Tuanduimao\Tuan as Tuan;
use \Tuanduimao\Excp as Excp;
use \Tuanduimao\Conf as Conf;


class CosController extends \Tuanduimao\Loader\Controller {
	
	function __construct() {
	}

	function test() {
		Utils::out( $_FILES );
	}

	/**
	 * 上传文件接口
	 * @return [type] [description]
	 */
	function upload() {

		$file = !empty($_FILES['wxfile']) ? $_FILES['wxfile'] : [];
		$content = !empty($file['content']) ? base64_decode($file['content']) : NULL;
		$filetype = Utils::mimes()->getExtension($file['type']);
		
		if ( $content == null ) {
			echo (new Excp("未接收到文件",  502, ['_FILES'=>$_FILES]))->toJSON();
			return;
		}

		$config = $GLOBALS['_QC']['cos'];
		$cos = App::M('Cos',$config);
		try { 
			$resp = $cos->upload( $content, ['region'=>$config['region'], 'filetype'=>$filetype] );
		} catch( Excp $e ){
			$extra = $e->getExtra();
			echo (new Excp("COS API 错误",  502, ['resp'=>$resp, 'e'=>$extra]))->toJSON();
			return;
		}
		if ( $resp['code'] == 0) {
			Utils::out($resp['data']);
			return;
		}
		echo (new Excp("COS API 错误",  502, ['resp'=>$resp]))->toJSON();
		return;

	}
	
}